﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using ETWJ.DTO;
using ETWJ.Iservice;
using ETWJ.Model;
using ETWJ.Service;
using Microsoft.AspNetCore.Mvc;

namespace ETWJ.ERP.Controllers
{
    public class OrderController : Controller
    {

        public IOrderService<Order,OrderDTO> orderService { get; set; }
        public IProductService<Product,ProductDTO> productService { get; set; }
        public ICompanyService<Company,CompanyDTO> companyService { get; set; }
        public IProductOrderService<ProductOrder,ProductOrderDTO> productOrderService { get; set; }

        public OrderController(
            IOrderService<Order, OrderDTO> orderService, 
            IProductService<Product, ProductDTO> productService, 
            ICompanyService<Company, CompanyDTO> companyService,
            IProductOrderService<ProductOrder, ProductOrderDTO> productOrderService
            )
        {
            this.orderService = orderService;
            this.productService = productService;
            this.companyService = companyService;
            this.productOrderService = productOrderService;
        }

        public IActionResult Index()
        {
            return View();
        }

        public async Task<IActionResult> List(int pageIndex=1,int count=5)
        {
            if (pageIndex <= 0)
            {
                pageIndex = 1;
            }
            var model = await orderService.GetOrderByPage(pageIndex, count);

            var totalCount = await orderService.GetOrderCountAsync();
            var currentPageIndex = pageIndex;
            var pageCount = Math.Ceiling(totalCount / 5.0);

            ViewBag.PageCount = pageCount;
            ViewBag.CurrentPageIndex = currentPageIndex;

            return View(model);
        }

        public async Task<IActionResult> Add()
        {

            ProductOrderAddModel model = new ProductOrderAddModel();

            var companys = await companyService.GetALL();
            var products = await productService.GetALL();

            model.Companys = companys;
            model.Products = products;

            return View(model);
        }

        [HttpPost]
        public async Task<IActionResult> AddOrder(AddOrderPostModel model)
        {
            string orderCode = Guid.NewGuid().ToString(); //生成一个订单编号  

            Order order = new Order();
            order.OrderCode = orderCode;
            order.OrderSumMoney = model.OrderSumMoney;
            order.OrderTime = model.OrderTime;
            order.SinglePeople = model.SinglePeople;
            order.CompanyId = model.CompanyId;
            order.DeliveTime = model.DeliveTime;

            int addOrderResult= await orderService.AddNewAsync(order); // 添加订单
            if (addOrderResult <= 0)
            {
                return RedirectToAction("Tip", "Home", new { redirectUrl = "/Order/List", msg = "添加订单失败！", isSuccess = "error" });
            }

            foreach (var item in model.Products)
            {
                ProductOrder productOrder = new ProductOrder();
                productOrder.Num = item.Num;
                productOrder.OrderCode = orderCode;
                productOrder.OrderId = order.Id;
                productOrder.ProductId = item.Id;
                await productOrderService.AddNewAsync(productOrder);
            }

            //return RedirectToAction("Tip", "Home", new { redirectUrl = "/Order/List", msg = "添加订单成功！", isSuccess = "ok" });
            return Json(new { isSuccess="ok" });
        }

        public async Task<IActionResult> GetEditOrder(int orderId)
        {
            // 获取订单下的所有商品
            var orderProducts = await productOrderService.GetProductByOrderId(orderId);
            return Json(new { data=orderProducts});
        }

        public async Task<IActionResult> Edit(int id)
        {
            // 获取订单
            var order = await orderService.GetByIdAsync(id);
            if (order == null)
            {
                return RedirectToAction("Tip", "Home", new { redirectUrl = "/Order/List", msg = "不存在该订单！", isSuccess = "error" });
            }
            // 获取订单下的所有商品
            var orderProducts= await productOrderService.GetProductByOrderId(order.Id);

            var companys = await companyService.GetALL(); // 所有的公司
            var products = await productService.GetALL(); // 所有的商品

            ProductOrderEditModel model = new ProductOrderEditModel();
            model.Products = products;
            model.OrderProducts = orderProducts;
            model.Companys = companys;
            model.Order = order;

            ViewBag.OrderProducts = orderProducts;

            ViewBag.OrderId = order.Id;

            return View(model);
        }

        [HttpPost]
        public async Task<IActionResult> Edit(ProductOrderEditPostModel model)
        {
            // 1. 查找订单
            var order=await orderService.GetByIdAsync(model.OrderId);
            if (order == null)
            {
                return RedirectToAction("Tip", "Home", new { redirectUrl = "/Order/List", msg = "该订单不存在！", isSuccess = "error" });
            }

            // 2. 更新订单
            order.CompanyId = model.CompanyId;
            order.DeliveTime = model.DeliveTime;
            order.OrderSumMoney = model.OrderSumMoney;
            order.OrderTime = model.OrderTime;
            order.SinglePeople = model.SinglePeople;
            var updateOrder= await orderService.Update(order);
            if(updateOrder<0)
            {
                return RedirectToAction("Tip", "Home", new { redirectUrl = "/Order/List", msg = "更新订单失败！", isSuccess = "error" });
            }

            // 3. 更新订单中的商品
            // 3.1 先将所有的订单删除，然后再添加
            if(model.Products.Count()>0)
            {
                foreach (var item in model.Products)
                {
                    await productOrderService.DeleteProByPrIdAndProCode(item.Id,order.OrderCode);
                }
            }

            foreach (var item in model.Products)
            {
                ProductOrder dto = new ProductOrder();
                dto.Num = item.Num;
                dto.OrderCode = order.OrderCode;
                dto.ProductId = item.Id;
                dto.OrderId = order.Id;

                await productOrderService.AddNewAsync(dto);
            }
            return Json(new { isSuccess="ok"});

        }
    }
}